import 'package:duqin/components/song_card.dart';
import 'package:duqin/models/song_model.dart';
import 'package:duqin/services/song_service.dart';
import 'package:flutter/material.dart';

class SongPage extends StatefulWidget {
  const SongPage({Key? key}) : super(key: key);

  @override
  _SongPageState createState() => _SongPageState();
}

class _SongPageState extends State<SongPage> {
  List<SongInfo> _songList = [];
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool err = false;
  String errMsg = '';

  @override
  void initState() {
    super.initState();
    _getSongList();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: _songList.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: [
              SizedBox(
                height: 10,
              ),
              SongCard(info: _songList[index]),
            ],
          );
        });
  }

  /// 获取歌曲列表
  Future<void> _getSongList({bool isFresh = true}) async {
    try {
      Map<String, dynamic> result =
          await SongService.getSongs(page: page, limit: limit);
      var songList = SongList.fromJson(result['data']);
      setState(() {
        //是否还有更多
        hasMore = this.page * this.limit < result['total'];
        this.page++;

        if (isFresh) {
          _songList = songList.list;
        } else {
          _songList.addAll(songList.list);
        }
      });
    } catch (e) {
      setState(() {
        err = true;
        errMsg = e.toString();
      });
    } finally {
      loading = false;
    }
  }
}
